<?php

namespace Biz\service;

use Biz\cache\PhotoRelaGoodsIds;
use Biz\cache\PicRelaGoodsIds;
use Biz\cache\wiki\WikiFavorite as cWikiFavorite;
use Biz\model\GoodsBasicInfo as mGoodsBasicInfo;
use Biz\model\PhotoRelaGoods as mPhotoRelaGoods;
use Biz\model\ShopFavorite as mShopFavorite;
use Biz\model\wiki\SpuRelateWiki;
use Doraemon\cache\UserCounter;
use Doraemon\model\PhotoRelaGoods as DmPhotoRelaGoods;
use Doraemon\model\PicStickers;
use Doraemon\model\UserRelaGoods;
use Doraemon\model\UserRelaGoods as mUserRelaGoods;
use Doraemon\tools\HhzClient;
use Doraemon\tools\Log;


class ShopGoodsOperator
{
    /**
     * 根据wiki获上线商品的ID
     * @param $wiki_id
     * @return mixed
     */
    private static function cliGetGoodsIdsByWikiIds($wiki_ids)
    {
        $infos = $wiki_ids ? mGoodsBasicInfo::getInfos([
            'wiki_id' => $wiki_ids,
            'status' => mGoodsBasicInfo::$statusAppNormalMap,
        ]) : [];

        $Rst = [];
        if ($infos) foreach ($infos as $info) {
            $Rst[$info['wiki_id']][] = $info['goods_id'];
        }

        return $Rst;
    }


    /**
     * wiki 转 spu 根据wikiID 替换为 收藏商品
     * @param $wiki_id
     *
     */
    public static function cliFavoriteByWikiId($wiki_id)
    {
        $infos = mUserRelaGoods::getByWikiId($wiki_id);
        $favInfos = [];
        foreach ($infos as $info) {
            if ($info['is_fav']) {
                $favInfos[$info['uid']][] = [
                    'wiki_id' => $info['spu_id'],
                    'fav_time' => $info['fav_time'],
                ];
            }
        }
        $goodsIds = self::cliGetGoodsIdsByWikiIds($wiki_id);

        if ($goodsIds && isset($goodsIds[$wiki_id]) && $goodsIds[$wiki_id]) {
            UserRelaGoods::updateData(['is_has_goods' => 1], [
                'id' => array_column($infos, 'id')
            ]);
        } else {
            UserRelaGoods::updateData(['is_has_goods' => 0], [
                'id' => array_column($infos, 'id')
            ]);
        }
        foreach ($favInfos as $uid => $favInfoGrpUid) {
            foreach ($favInfoGrpUid as $favInfo) {
                if (isset($goodsIds[$favInfo['wiki_id']])) {
                    $is_favorite = mShopFavorite::is_favorited($uid, $goodsIds[$favInfo['wiki_id']], mShopFavorite::TYPE_GOODS);
                    if (!array_filter($is_favorite)) {
                        $randomGoodsId = $goodsIds[$favInfo['wiki_id']][array_rand($goodsIds[$favInfo['wiki_id']])];
                        return self::favorite($uid, $randomGoodsId, mShopFavorite::TYPE_GOODS);
                    }
                }
            }
        }

    }

    /**
     *
     * @param $uid
     * @param $wiki_id
     */

    public static function cliRelaPhotosByWikiId($wiki_id)
    {
        $goods_ids_grp_wikiid = self::cliGetGoodsIdsByWikiIds($wiki_id);
        $goods_ids = isset($goods_ids_grp_wikiid[$wiki_id]) ? $goods_ids_grp_wikiid[$wiki_id] : [];
        $relaInfos = DmPhotoRelaGoods::select("*", [
            'OR' => [
                'goods_id' => $wiki_id,
                'other_id' => $wiki_id,
            ],
            'status' => DmPhotoRelaGoods::STATUS_NORMAL
        ]);

        $relaInfo = [];
        foreach ($relaInfos as $item) {
            $relaInfo[$item['photo_id']] = [
                'goods_id' => $item['goods_id'] ? $item['goods_id'] : $item['other_id'],
                'uid' => $item['uid'],
                'is_admin' => $item['isadmin'],
                'addtime' => $item['addtime'],
            ];
        }

        foreach ($relaInfo as $photo_id => $info) {
            if ($goods_ids) {
                $is_rela_goods = mPhotoRelaGoods::is_rela_goods($photo_id, $goods_ids);
                if (!array_filter($is_rela_goods)) {
                    return self::PhotoRelaGoods($photo_id, $goods_ids[array_rand($goods_ids)], $info['uid'], $info['is_admin'] ? mPhotoRelaGoods::TYPE_ARTIFICIAL : mPhotoRelaGoods::TYPE_WIKI_TO_SPU, false, $info['addtime']);
                }
            }
        }
    }


    public static function PhotoRelaGoods($noteId, $picId, $goods_id, $uid, $type, $is_force = false, $addtime = null)
    {
        $is_rela_goods = $is_force ? false : mPhotoRelaGoods::is_rela_goods($picId, [$goods_id])[$goods_id];
        if ($is_rela_goods) {
            throw new \Exception('不可重复关联');
        }
        self::checkObjStatus($goods_id, mShopFavorite::TYPE_GOODS);
        PhotoRelaGoodsIds::delItem($noteId);
        return mPhotoRelaGoods::addRela($noteId, $picId, $goods_id, $uid, $type, $addtime);

    }

    public static function PhotoRelaGoodsTag($picId, array $goodsIds, $uid)
    {
        Log::wiki_PhotoRelaGoodsTag_info("图片关联商品#" . $picId . "#data:" . json_encode(['pic_id' => $picId, 'goods_ids' => $goodsIds, 'uid' => $uid]));
        $picSticker = PicStickers::getStickerByPicId($picId);
        $allRelaGoodsIds = mPhotoRelaGoods::getAllRelateGoodsIds($picId);
        Log::wiki_PhotoRelaGoodsTag_info('图片关联商品#' . $picId . '#已经关联的商品Id:' . json_encode($allRelaGoodsIds));
        foreach ($goodsIds as $goodsId) {
            self::checkObjStatus($goodsId, mShopFavorite::TYPE_GOODS);
            PhotoRelaGoodsIds::delItem($picSticker['note_id']);
            mPhotoRelaGoods::addRela($picSticker['note_id'], $picId, $goodsId, $uid, mPhotoRelaGoods::TYPE_USER_TAG, date("Y-m-d H:i:s"));
        }

        if (!empty($allRelaGoodsIds)) {
            $delGoodsIds = array_diff($allRelaGoodsIds, $goodsIds);
            Log::wiki_PhotoRelaGoodsTag_info('图片关联商品#' . $picId . '#取消关联的goodsIds:' . json_encode($delGoodsIds));
            if ($delGoodsIds) {
                $where = [];
                $where['obj_id'] = $picSticker['note_id'];
                $where['obj_type'] = 1;
                $where['rel_obj_id'] = $picId;
                $where['rel_obj_type'] = 1;
                $where['goods_id'] = $delGoodsIds;
                $where['uid'] = $uid;
                $where['type'] = mPhotoRelaGoods::TYPE_USER_TAG;
                mPhotoRelaGoods::updateRelaInfos(['status' => mPhotoRelaGoods::STATUS_DEL], $where);
            }
        }
        PicRelaGoodsIds::delItem($picSticker['note_id']);
    }


    public static function UnFavoriteByWikiId($uid, $wiki_id)
    {
        $goods_ids = self::cliGetGoodsIdsByWikiIds([$wiki_id])[$wiki_id];
        mShopFavorite::UnFavorite($uid, $goods_ids, mShopFavorite::TYPE_GOODS);

    }


    /**
     * 收藏
     * @param $uid
     * @param $objId int 对象ID
     * @param $objType int 对象类型
     * @param $appSource int 来源
     * @return mixed
     * @throws \Exception
     */
    public static function favorite($uid, $objId, $objType, $appSource = 0)
    {
        $is_favorite = mShopFavorite::is_favorited($uid, [$objId], $objType, $appSource)[$objId];
        if ($is_favorite) {
            throw new \Exception('请勿重复操作');
        }
        self::checkObjStatus($objId, $objType, ['fav'], $appSource);
        $rowCount = mShopFavorite::add_favorite($uid, $objId, $objType, $appSource);
        if ($rowCount) {
            //用户收藏商品数累加
            self::incrUserCounter($uid, $objType, $appSource);

            //wiki添加收藏数
            if ($objType == mShopFavorite::TYPE_WIKI) {
                cWikiFavorite::increaseCounter($objId);
            }
            return $rowCount;
        }
    }

    private static function incrUserCounter($uid, $type, $appSource)
    {
        if ($appSource != HhzClient::APPTYPE_PARAGRAPH_MINIPROGRAM) {
            if (in_array($type, [mShopFavorite::TYPE_GOODS, mShopFavorite::TYPE_WIKI])) {
                UserCounter::increaseUserCounter($uid, UserCounter::TYPE_FAVORITE_SPU);
            }
        }
    }

    private static function decrUserCounter($uid, $type)
    {
        if (in_array($type, [mShopFavorite::TYPE_GOODS, mShopFavorite::TYPE_WIKI])) {
            UserCounter::decreaseUserCounter($uid, UserCounter::TYPE_FAVORITE_SPU);
        }
    }

    /**
     * 取消收藏
     * @param $uid
     * @param $objId
     * @param $objType
     * @param $appSource
     * @return mixed
     * @throws \Exception
     */
    public static function Unfavorite($uid, $objId, $objType, $appSource = 0)
    {
        $is_favorite = mShopFavorite::is_favorited($uid, [$objId], $objType, $appSource)[$objId];

        if (!$is_favorite && $objType == mShopFavorite::TYPE_WIKI) {
            //查询转换wiki
            $objId = SpuRelateWiki::getWikiExists($objId);
            if ($objId > 0) {
                $objType = mShopFavorite::TYPE_GOODS;
                $is_favorite = mShopFavorite::is_favorited($uid, [$objId], $objType, $appSource)[$objId];
            }
        }
        if (!$is_favorite) {
            throw new \Exception('请勿重复操作');
        }
        self::checkObjStatus($objId, $objType);
        $rowCount = mShopFavorite::UnFavorite($uid, $objId, $objType, $appSource);
        if ($rowCount) {
            self::decrUserCounter($uid, $objType);

            //wiki减少收藏数
            if ($objType == mShopFavorite::TYPE_WIKI) {
                cWikiFavorite::decreaseCounter($objId);
            }
        }
    }

    /**
     *
     * 验证对象ID
     * @param $obj_id
     * @param $obj_type
     * @throws \Exception
     *
     */
    private static function checkObjStatus($obj_id, $obj_type, $scenes = [], $appSource = 0)
    {
        if ($obj_type == mShopFavorite::TYPE_GOODS) {
            $goodsDetail = GoodsDetail::formatBasicInfos([$obj_id]);
            if (!isset($goodsDetail[$obj_id])) {
                throw new \Exception('商品不存在');
            }
        }
    }

}